"""
邮件发送工具
"""
import aiosmtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from backend.app.utils.config import settings
import asyncio
from backend.app.utils.logger import logger

async def send_verification_email(email: str, code: str, max_retries: int = 1):
    """
    发送验证码邮件，失败时自动重试
    
    Args:
        email: 接收者邮箱
        code: 验证码
        max_retries: 最大重试次数
    """
    message = MIMEMultipart()
    message["From"] = settings.FROM_EMAIL
    message["To"] = email
    message["Subject"] = "TellTech 验证码"

    # 邮件内容
    body = f"""
    <html>
        <body>
            <h2>TellTech 验证码</h2>
            <p>您的验证码是：<strong>{code}</strong></p>
            <p>验证码有效期为1分钟，请尽快使用。</p>
            <p>如果这不是您的操作，请忽略此邮件。</p>
        </body>
    </html>
    """
    
    message.attach(MIMEText(body, "html"))

    # 发送邮件（带重试机制）
    retries = 0
    while retries <= max_retries:
        try:
            await aiosmtplib.send(
                message,
                hostname=settings.SMTP_SERVER,
                port=settings.SMTP_PORT,
                username=settings.FROM_EMAIL,
                password=settings.AUTH_CODE,
                use_tls=True
            )
            logger.info(f"邮件发送成功: {email}")
            return
        except Exception as e:
            retries += 1
            if retries <= max_retries:
                logger.warning(f"邮件发送失败，正在进行第{retries}次重试: {str(e)}")
                await asyncio.sleep(1)  # 等待1秒后重试
            else:
                logger.error(f"邮件发送失败，已达到最大重试次数: {str(e)}")
                raise 